import type { MenuList, MenuState } from '@/store/module/menuModule'

const viewModules = import.meta.glob('@/views/**/*.vue')

export const arrayToTree = (data: MenuList[]): MenuList[] => {
  const map: Record<string, MenuList> = {}; // 用于存储每个节点
  const roots: MenuList[] = []; // 存储根节点

  // 首先创建一个 map，方便快速查找每个菜单项
  data.forEach(item => {
    map[item.menu_id] = { ...item, children: [] }; // 初始化每个节点的 children 属性
  });

  // 遍历数据，将每个节点挂载到其父节点的 children 数组中
  data.forEach(item => {
    if (item.parent_id === null || !map[item.parent_id as string]) {
      // 如果没有父节点，说明是根节点
      roots.push(map[item.menu_id]);
    } else{
      // 如果有父节点，将当前项添加到父节点的 children 数组中
      const parent = map[item.parent_id as string];
      if ( parent.children) {
        parent.children.push(map[item.menu_id]);
      }
    }
  });

   const cleanChildren = (nodes: any[]): MenuList[] => {
    return nodes.map<MenuList>(node => {
      const { children, ...rest } = node;
      if (children && children.length > 0) {
        return { ...rest, children: cleanChildren(children) }; // 保留非空 children
      }
      const { children: _, ...cleanedNode } = node; // 移除空的 children
      return cleanedNode; // 返回处理后的节点
    });
  };

  return cleanChildren(roots);
};
export const transformAsyncMenus = (menus: any) => {
  const newMenus = menus.map((menu: any) => {
    if (menu.children && menu.children.length > 1 ) {
      return {
        path: `/${menu.path || ''}`,
        name: menu.name,
        meta: {
          title: menu.title,
          icon: menu.icon,
        },
        children: transformAsyncMenus(menu.children),
      }
    } else if (menu.children && menu.children.length === 1 ) {
      console.log('我应该打印两次',menu)
      return {
        path: `/${menu.path || ''}`,
        name: menu.name,
        meta: {
          title: menu.title,
          icon: menu.icon,
        },
        children: transformAsyncMenus(menu.children),
      }
    } else {
      return {
        path: `/${menu.path}`,
        name: menu.name,
        icon: menu.icon,
        meta: {
          title: menu.title,
          icon: menu.icon,
        },
        component: viewModules[menu.component + '.vue'],
      }
    }
  })

  return newMenus
}

export const getBreadCrumbList = (route: any, homeRoute: any) => {
  let homeItem = { ...homeRoute, icon: homeRoute.meta.icon }
  let routeMetched = route.matched
  if (routeMetched.some((item: { name: any }) => item.name === homeRoute.name))
    return [homeItem]
  let res = routeMetched
    .filter((item: { name: undefined }) => {
      return item.name !== undefined
    })
    .map((item: { meta: { icon: any }; name: any }) => {
      let meta = { ...item.meta }
      let obj = {
        icon: (item.meta && item.meta.icon) || '',
        name: item.name,
        meta: meta,
      }

      return obj
    })
  return [{ ...homeItem, to: homeRoute.path }, ...res]
}

export const getHomeRoute = (routers: any[], homeName = 'home_page') => {
  let i = -1
  let len = routers.length
  let homeRoute = {}
  while (++i < len) {
    let item = routers[i]
    if (item.children && item.children.length) {
      let res: any = getHomeRoute(item.children, homeName)
      if (res.name) return res
    } else {
      if (item.name === homeName) homeRoute = item
    }
  }
  return homeRoute
}

export const timeFormat = (date: Date | string | number, fmt = 'yyyy-MM-dd hh:mm:ss'): string => {
  if (!date) return "";

  if (!date) return "";

  // 确保传入的date是Date类型，如果是数字或字符串则转换为Date
  if (typeof date === 'number' || typeof date === 'string') {
    date = new Date(date);
  }

  // 确保date是有效的Date对象
  if (!(date instanceof Date) || isNaN(date.getTime())) {
    return "";
  }

  let nowDate = date;

  // 格式化选项
  let opt: { [key: string]: number | string } = {
    "M+": nowDate.getMonth() + 1, // 月份
    "d+": nowDate.getDate(), // 日
    "h+": nowDate.getHours(), // 小时
    "m+": nowDate.getMinutes(), // 分钟
    "s+": nowDate.getSeconds(), // 秒
    "q+": Math.floor((nowDate.getMonth() + 3) / 3), // 季度
    "S": nowDate.getMilliseconds(), // 毫秒
  };

  // 处理年份（特殊情况，年份可以是两位或四位）
  let regex = new RegExp("(y+)");
  let fmtMatch = fmt.match(regex);
  if (fmtMatch) {
    fmt = fmt.replace(fmtMatch[1], (nowDate.getFullYear() + "").substr(4 - fmtMatch[1].length));
  }

  // 遍历并替换格式中的其他部分（M、d、h、m、s、q、S）
  for (let k in opt) {
    let regex = new RegExp("(" + k + ")");
    let fmtMatch = fmt.match(regex);
    if (fmtMatch) {
      fmt = fmt.replace(fmtMatch[1],
        (fmtMatch[1].length == 1) ? (opt[k] as string) : (("00" + (opt[k] as string)).substr(("" + opt[k]).length))
      );
    }
  }

  return fmt;
};

export const timeAgo = (date: Date | number): string => {
  // 确保输入是时间戳（数字）或者 Date 对象
  // 确保输入是时间戳（数字）或者 Date 对象
  const now = Date.now();
  // 如果传入的是 Date 对象，获取时间戳；如果传入的是数字，则直接使用该数字
  const targetTime = (date instanceof Date) ? date.getTime() : date;

  // 如果目标时间大于当前时间，返回 "1秒前"
  if (targetTime > now) {
    return '1秒前';
  }

  // 计算时间差，单位为秒
  const diffInSeconds = Math.floor((now - targetTime) / 1000);
  // 如果时间小于60秒，返回秒数
  if (diffInSeconds < 60) {
    return `${diffInSeconds}秒前`;
  } else if (diffInSeconds < 3600) { // 小于1小时，返回分钟
    const minutes = Math.floor(diffInSeconds / 60);
    return `${minutes}分钟前`;
  } else if (diffInSeconds < 86400) { // 小于1天，返回小时
    const hours = Math.floor(diffInSeconds / 3600);
    return `${hours}小时前`;
  } else if (diffInSeconds < 2592000) { // 小于30天，返回天数和小时数
    const days = Math.floor(diffInSeconds / 86400);
    const hours = Math.floor((diffInSeconds % 86400) / 3600);
    return `${days}天${hours}小时前`;
  } else if (diffInSeconds < 31536000) { // 小于1年，返回月份
    const months = Math.floor(diffInSeconds / 2592000);
    return `${months}个月前`;
  } else { // 大于1年，返回年份
    const years = Math.floor(diffInSeconds / 31536000);
    return `${years}年前`;
  }
}

export const timeRemaining = (target: Date | number, endText= '已过期'): string => {
  const now = Date.now();
  const targetTime = (target instanceof Date) ? target.getTime() : target;

  // 如果目标时间小于当前时间，返回已过期
  if (targetTime <= now) {
    return endText;
  }

  // 计算时间差，单位为毫秒
  const diffInMs = targetTime - now;
  const diffInSeconds = Math.floor(diffInMs / 1000);

  // 小于60秒
  if (diffInSeconds < 60) {
    return `${diffInSeconds}秒`;
  }

  // 小于60分钟
  if (diffInSeconds < 3600) {
    const minutes = Math.floor(diffInSeconds / 60);
    return `${minutes}分钟`;
  }

  // 小于24小时
  if (diffInSeconds < 86400) {
    const hours = Math.floor(diffInSeconds / 3600);
    const minutes = Math.floor((diffInSeconds % 3600) / 60);
    return `${hours}小时${minutes}分钟`;
  }

  // 小于30天
  if (diffInSeconds < 2592000) {
    const days = Math.floor(diffInSeconds / 86400);
    const hours = Math.floor((diffInSeconds % 86400) / 3600);
    return `${days}天${hours}小时`;
  }

  // 超过30天的按天显示
  const days = Math.floor(diffInSeconds / 86400);
  return `${days}天`;
};
